<!DOCTYPE html>
<html lang="en">
<head>
	<title>nowjs test</title>

	<link href="/content/site.css" rel="stylesheet" type="text/css" />
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
	<script src="/nowjs/now.js"></script>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.0.0/knockout-min.js" type="text/javascript"></script>
</head>

<body class="page">
	 <div id="gameResults" hidden="hidden">
		<h3>Results</h3>
		<table data-bind="foreach: gameResults()">
			<tr>
				<td data-bind="text: gamePlace">||hallo</td>
				<td data-bind="text: gameParticipant"></td>
				<td data-bind="text: gameBalance"></td>
			</tr>
		</table>
	</div>
	<div id="game">
	<header id="userInfo">
		Credit: <span data-bind="text: balance"></span> | Name:<span data-bind="text: name"></span> | <span data-bind="text: countDown"></span>
	</header>
	<header id="stock-scrollbar">
		<marquee id="scrollbar" data-bind="foreach: stocks()">
			<img data-bind="attr: { src: stockImage} " />
			<span data-bind="text: stockName"></span> -
			<span data-bind="text: stockPrice"></span> /
		</marquee>
	</header>
	
	<section>
		<nav id="column-1" class="columns">
			<p class="subtittle">Online user</p>
			<div id="userList">
				<ul data-bind="foreach: onlineUsers()">
					<li >
						<a href="#" data-bind="click: $parent.chat">Add To Chat</a>
						<span data-bind="text: userName"></span>
					</li>
				</ul>
			</div>	
			<span class="note">note: Users will be added to current room.</span>
		</nav>
		
		<div id="column-2" class="columns">
			<p class="subtittle">My Stocks</p>
			<div id="myStockList">
				<ul data-bind="foreach: myStocks()">
					<li>
						<a href="#" data-bind="click: $parent.sell">Sell</a>
						<input data-bind="value: sellHowMany"></input>
						<span data-bind="text: myStockName"></span>
						<span data-bind="text: myUnits"></span>
						<span data-bind="text: myStockPrice"></span> 
						
					</li>
				</ul>
			</div>			
		</div>
		
		<div id="column-3" class="columns">
			<p class="subtittle">Available Stocks</p>
			<div id="stockList">
				<ul data-bind="foreach: stocks()">
					<li>
						<a href="#" data-bind="click: $parent.buy">Buy</a>
						<input data-bind="value: buyHowMany"></input>
						<img data-bind="attr: { src: stockImage} " />
						<span data-bind="text: stockName"></span> 
						<span data-bind="text: stockPrice"></span>
							
					</li>
				</ul>
			</div>
		</div>
		
		<div class="clear"></div>
	</section>
	
	<footer id="footer">
	
		<div id="chatlist">
			<p class="subtittle-chat">Chat Messages</p>
			<div id="messages"></br>You're in Main</div>
			<input type="text" id="text-input">
			<input type="button" value="Send" id="send-button">
		</div>
		
		<div id="roomslist">
			<p class="subtittle-chat">Chat Rooms</p>
			<input type="text" data-bind="value: chatName"/>
			<input type="button" value="Create Room" data-bind="click: addChat"/>
			<ul id="main-room">
				<li><a href="#" data-bind="click: function(){ changeRoom('Main Room')}">Main Room</a></li>
			</ul>
			<ul id="rooms" data-bind="foreach: myChatRooms()">
				  <li>
					<a href="#" data-bind="click: $parent.changeRoom">
						<span data-bind="text: roomName"></span> | members:
						<span data-bind="text: chatMembers"></span>
					</a>
				  </li>
			</ul>  
		</div>
		
		<div class="clear"></div>
	</footer>
	</div>
</body>

<script type="text/javascript">
	$(document).ready(function(){
	  var stockModel = new stockViewModel();
	  ko.applyBindings(stockModel);
	  //initialize stockModel variables
	  now.initializeStockInfo = function(stockList, user, onlineUsers){
		stockModel.stockInfo( stockList);
		stockModel.userInfo(user);
		stockModel.updateUserList(onlineUsers);
	  }
	  //when game is over switch div and show results
	  now.gameOver = function(results){
		showResults();
		stockModel.gameIsOver(results);
	  }
	  //Update online users list
	  now.updateOnlineUser = function(onlineUsers){
		stockModel.updateUserList(onlineUsers);
	  } 
	  //update counter LISTENER!
	  now.countDownTime = function(timeLeft){
		stockModel.timer(timeLeft);
	  }
	  //Update the stock list and scroll bar	  
	  now.updateStockInfo = function(stockList){
		stockModel.stockInfo(stockList);
	  }
	  //Update user header and stock
	  now.updateUserStockInfo = function(user){
		stockModel.userInfo(user);	
	  }
	  //callback for updating stocks upon sell and buy
	  now.updateMyStockPrices = function(stockName){
		now.updateMyStock(stockName);
	  }	  
	  //Updates users ChatList
	  now.addChatRoom = function(userRooms){
		stockModel.updateUserChatRooms(userRooms);
	  }
	  //Get response from user for identifying which user was added to a chat room
	  now.getUserResponse = function(roomName, clientId){
	  	now.userResponseForChat(roomName, clientId);
	  }
	  //Get User response for identifying and updating chat room member for users in that chat room
	  now.getUserChatUpdateResponse = function(roomName){
	  	now.userResponseForChatRoomUpdate(roomName);
	  }	  
	  //Let user update his chat rooms
	  now.updateChatRoomListMembers = function(userRooms){
		stockModel.updateUserChatRooms(userRooms);
	  }
	  //Listener for recieving messages  
	  now.receiveMessage = function(name, message){
		$("#messages").append("<br>" + name + ": " + message);
	  }
	  //Event handler for sending messages
	  $("#send-button").click(function(){
		now.distributeMessage($("#text-input").val());
		$("#text-input").val("");
	  });
	  now.name = prompt("What's your name?", "");
	});
	
	//hide game and show results
	function showResults(){
		$("#game").hide();
		$("#gameResults").show();
	}
	//THE ViewModel
	function stockViewModel( ){
		var self = this;
		self.name = ko.observable("");
		self.balance = ko.observable("");
		self.countDown = ko.observable("--:--:--");
		self.chatName = ko.observable("");
		self.stocks = ko.observableArray([]);
		self.myStocks = ko.observableArray([]);
		self.myChatRooms = ko.observableArray([]);
		self.gameResults = ko.observableArray([]);
		self.onlineUsers = ko.observableArray([]);
		
		//update all Available Stocks
		self.stockInfo = function(stockList){
			this.stocks.removeAll();
			for(var i = 0 ; i < stockList.length; i++){
				this.stocks.push( new Stock( stockList[i].name, stockList[i].price, stockList[i].raised));
			}
		}
		//update user header and user stocks
		self.userInfo = function(user){
			this.name(user.name);
			this.balance("$" + user.balance);
			this.myStocks.removeAll();
			for(var i = 0 ; i < user.stocks.length ; i++){
				this.myStocks.push(new MyStock(user.stocks[i].name, user.stocks[i].units, user.stocks[i].price));
			}
		}
		//update user ChatRooms
		self.updateUserChatRooms = function(userChatRooms){
			this.myChatRooms.removeAll();
			for(var i = 0; i < userChatRooms.length ; i++){
				this.myChatRooms.push(new ChatRoom(userChatRooms[i].name, userChatRooms[i].members));
			}
		}
		//function buy, send message to server
		self.buy = function(stockItem){
			now.buyStock(stockItem.stockName(), stockItem.buyHowMany());	
		}
		//function sell, send message to server
		self.sell = function(myStockItem){
			now.sellStock(myStockItem.myStockName(), myStockItem.sellHowMany());
		}
		//function timer, update time from server
		self.timer = function(timeLeft){
			this.countDown(timeLeft);
		}
		//function chat, send to server who user want to add to chatRoom
		self.chat = function(users){
			now.addUserToChat(users.userId(), users.userName());
		}
		//function addChat, add new personal ChatRoom
		self.addChat = function(){
			if(this.chatName() == ""){
				alert("Room name cannot be empty");
			}
			else{
				now.createChatRoom(this.chatName());
				this.chatName("");
			}	
		}
		//function changeRoom, send to server which chatRoom user wants to partisipate in
		self.changeRoom = function(chatRoom){
			if(chatRoom == "Main Room"){
				now.changeRoom(chatRoom);
			}
			else{
				now.changeRoom(chatRoom.roomName());
			}
		}
		//function updateUserList, updates online userList from server
		self.updateUserList = function(allUsers){		
			this.onlineUsers.removeAll();
			for(var i = 0; i < allUsers.length; i++){
				this.onlineUsers.push(new Users(allUsers[i].name,allUsers[i].id));
			}
		}
		//function gameIsOver, Add to table gameResults
		self.gameIsOver = function(results){
			this.gameResults.removeAll();
			for(var i = 0 ; i < results.length ; i++){
				this.gameResults.push(new userResult((i+1) + ". place", results[i].name, "$" + results[i].balance));
			}	
		}
		//Model userResults
		function userResult(gamePlace, gameParticipant, gameBalance){
			var self = this;
			self.gamePlace = ko.observable(gamePlace);
			self.gameParticipant = ko.observable(gameParticipant);
			self.gameBalance = ko.observable(gameBalance);
		}
		//Model ChatRoom, for user Chat Rooms
		function ChatRoom(roomName, members){
			var self = this;
			self.roomName = ko.observable(roomName);
			var allMembers = ("");
			for(var i = 0; i < members.length ; i++){
				allMembers = allMembers + members[i].name + " - ";
			}
			self.chatMembers = ko.observable(allMembers);
		}
		//Model Users, for online Users
		function Users(userName, userId){
			var self = this;
			self.userName = ko.observable(userName);
			self.userId = ko.observable(userId);
		}
		//Model MyStock, for users stocks
		function MyStock(myStockName, myUnits, myStockPrice){
			var self = this; 
			self.myStockName = ko.observable(myStockName);
			self.myUnits = ko.observable(myUnits);
			self.sellHowMany = ko.observable(1);
			self.myStockPrice = ko.observable("$" +myStockPrice);
		}
		//Model Stock, for All Available stocks
		function Stock(stockName, stockPrice, raised){
			var self = this;
			self.stockName = ko.observable(stockName);
			self.stockPrice = ko.observable("$" +stockPrice);
			self.stockIsRaised = ko.observable(raised);
			self.buyHowMany = ko.observable(1);
			self.stockImage = ko.computed(function(stock){
				if(raised == true){
					return "/content/Images/stock_index_up.png";
				}
				else{
					return "/content/Images/stock_index_down.png";
				}
			});
		}	
	}
	
</script>
</html>